package com.company.psm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.company.psm.entity.User;
import com.company.psm.service.UserManagement;

@Controller
@RequestMapping("/")
public class LoginController {
	@Autowired
	private UserManagement userManagement;
	@RequestMapping(value = "/login/welcome", method = RequestMethod.GET)
	public ModelAndView welcomePage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Custom Login Form");
		model.addObject("message", "This is welcome page!");
		model.setViewName("welcome");
		return model;
	}
	@RequestMapping(value = "/j_spring_security_check", method = RequestMethod.GET)
	public ModelAndView logout() {
		ModelAndView model = new ModelAndView();
		model.setViewName("/");
		return model;
	}
	@RequestMapping(value = "/account**", method = RequestMethod.GET)
	public ModelAndView adminPage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Custom Login Form");
		model.addObject("message", "This is protected page!");
		model.setViewName("admin");

		return model;

	}

	// Spring Security see this :
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(
			@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout) {
		ModelAndView model = new ModelAndView();
		User user = getCurrentUser();
		if (error != null) {
			model.addObject("error", "Thông tin đăng nhập không đúng!");
			model.setViewName("/login");
		}

		if (logout != null) {
			model.addObject("msg", "Bạn đã đăng xuất thành công");
			model.setViewName("/login");
		}
		return model;

	}
    public User getCurrentUser(){
    	Authentication authentication = SecurityContextHolder.getContext().
      		  getAuthentication();
      		  String name = authentication.getName();
      	return userManagement.getUserByAccount(name);
    }
	@RequestMapping(value = "/adminCpanel",method = RequestMethod.GET)
	public ModelAndView adminCpanel(){
		return new ModelAndView();
	}
	@RequestMapping(value = "/activerequire", method = RequestMethod.GET)
	public ModelAndView activerequire() {

		ModelAndView model = new ModelAndView();
		model.setViewName("/activerequire");
		return model;
	}
}
